package playlist;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import config.ConfigFile;

public class Composer {
	private Map<String, List<File>> mp3s;
	
	public Composer(Map<String, List<File>> someMp3s) {
		mp3s = someMp3s;
	}

	public List<File> compose(String type) throws Throwable {
		List<File> playlist = new ArrayList<File>();
		String currentType = ComposerConfig.getStartType(type);
		int playlistSize = 10000;
		
		try {
			playlistSize = Integer.parseInt(ConfigFile
					.getProperty("playlistSize"));
		} catch (NumberFormatException nfe) {
			// If unparsable, default value stays 10000.
		}
			

		for (int i = 0; i < playlistSize; i++) {
			File mp3 = extractRandomMp3(currentType);
			
			if (mp3 == null) {
				// Degraded case
				System.out.println("Error : Stop playlist "
					+ "creation for type : " + type);
				break;
			}
			playlist.add(mp3);
			currentType = ComposerConfig.getNewTransition(type);
		}
		return playlist;
	}

	/*
	 * Mp3 are removed from list as they are extracted
	 */
	private File extractRandomMp3(String currentType) {
		List<File> typeList = mp3s.get(currentType);
		if ((typeList == null) || (typeList.size() == 0)) {
			// Degraded case
			System.out.println("Error : No more mp3 for type : "
				+ currentType);
			return null;
		}
		int typeListSize = typeList.size();
		int indix = (int) Math.floor(
			Math.random() * typeListSize);
		File mp3 = typeList.get(indix);
		typeList.remove(indix);
		return mp3;
	}

}
